package com.xunfei.mqtt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.xunfei.mqtt.mqtt.AndroidMqttClient
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    private lateinit var mqttClient: AndroidMqttClient
    private lateinit var connectionStatus : TextView

    private lateinit var messageLog: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        connectionStatus = findViewById(R.id.connectionStatus)
        messageLog = findViewById(R.id.messageLog)
        // 初始化 MQTT 客户端
        mqttClient = AndroidMqttClient(
            context = this,
            serverUri = "tcp://post-cn-7pp2nvr1q01.mqtt.aliyuncs.com:1883",
            clientId = "GID_car@@@4c10fbja",
            username1 = "Signature|LTAI5tR8Q5WUN7noxVSFUzyy|post-cn-7pp2nvr1q01",
            password1 = "i3pfpwveO1s4/3L72ItZ05LV12M="
        )

        // 观察连接状态
        mqttClient.connectionState.observe(this) { state ->
            when (state) {
                is AndroidMqttClient.ConnectionState.Connecting -> {
                    Log.d("MQTT", "Connecting...")
                }

                is AndroidMqttClient.ConnectionState.Connected -> {
                    Log.d("MQTT", "Connected")
                    // 连接成功后订阅主题
                    mqttClient.subscribe("number_topic_gears")
                    connectionStatus.text = "Connection Status: Connected"
                }

                is AndroidMqttClient.ConnectionState.Disconnected -> {
                    Log.d("MQTT", "Disconnected")

                    connectionStatus.text = "Connection Status: Disconnected"
                }

                is AndroidMqttClient.ConnectionState.Error -> {
                    Log.e("MQTT", "Connection Error: ${state.message}")
                }
            }
        }

        // 观察接收到的消息
        mqttClient.receivedMessages.observe(this) { (topic, message) ->
            Log.d("MQTT", "Received: Topic=$topic, Message=$message")
            messageLog.append("Received: Topic=$topic, Message=$message\n")
            // 更新 UI
        }

        // 连接到 MQTT 服务器
        mqttClient.connect()

        // 发布消息示例
        findViewById<Button>(R.id.publishButton).setOnClickListener {
            val message = "Hello from Android!"
            mqttClient.publish("test/topic", message)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 销毁 MQTT 客户端
        mqttClient.destroy()
    }
}